import { DOCUMENT } from '@angular/common';
import { ChangeDetectorRef, Component, inject, Inject, OnInit, ViewChild } from '@angular/core';
import { AfMessageService, AfNavigationService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { TitleService } from '@delon/theme';
import { SharedModule } from '@shared';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';

import { DemoService } from '../demo.service';

const getBase64 = (file: File): Promise<string | ArrayBuffer | null> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });

@Component({
  selector: 'app-demo-upload',
  standalone: true,
  imports: [SharedModule],
  providers: [DemoService],
  templateUrl: './upload.component.html'
})
export class DemoUploadComponent implements OnInit {
  private readonly demoSrv = inject(DemoService);
  private titleSrv = inject(TitleService);

  manuel_cst = '手动输入';
  constructor(
    private navSrv: AfNavigationService,
    private cdr: ChangeDetectorRef,
    private msgSrv: AfMessageService,
    @Inject(DOCUMENT) private document: Document
  ) {}

  images: any[] = ['https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'];
  actionUrl = '';
  fileList: NzUploadFile[] = [
    // {
    //   uid: '-1',
    //   name: 'image.png',
    //   status: 'done',
    //   message: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // },
    // {
    //   uid: '-5',
    //   name: 'image.png',
    //   status: 'error',
    //   message: 'done'
    // }
  ];

  ngOnInit(): void {
    this.titleSrv.setTitle('上传文件');
    this.actionUrl = this.demoSrv.getOssUploadFileUrl();

    this.buildFileList(JSON.stringify(this.images));
  }

  buildFileList(images: any) {
    if (!images) {
      return;
    }
    const list: string[] = JSON.parse(images);
    list.forEach((image, index) => {
      this.fileList.push({
        uid: `-1${index}`,
        name: 'image.png',
        status: 'done',
        url: image
      });
    });
  }

  loading = false;

  save() {
    const urls = this.fileList
      .filter(item => item.url) // 先过滤掉没有 url 属性的对象
      .map(item => item.url); // 然后从剩下的对象中提取 url 属性

    const body = {
      reasonImages: JSON.stringify(urls)
    };

    console.log('body', body);
  }

  previewImage: string | undefined = '';
  previewVisible = false;

  handlePreview = async (file: NzUploadFile): Promise<void> => {
    if (file.url) {
      this.previewImage = file.url;
      this.previewVisible = true;
    } else {
      if (file?.response) {
        if (file?.response.status) {
          this.previewImage = file?.response?.url;
          this.previewVisible = true;
        }
      }
    }
    // console.log('handlePreview', file);
  };

  handleChange2(info: NzUploadChangeParam): void {
    console.log('NzUploadChangeParam', info);
    if (info?.type === 'removed') {
      this.clearImage();
    }
    const file = info.file;
    // console.log(info);
    switch (file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.handleFileResponse(info.file, info.fileList);
        this.loading = false;
        break;
      case 'error':
        // this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  handleFileResponse(file: NzUploadFile, fileList: NzUploadFile[]) {
    console.log('file?.response', file?.response);
    if (file?.response.status) {
      const objectResult = file?.response.data;
      if (objectResult.code == 0) {
        if (objectResult.storageType == 'local') {
          file.url = this.navSrv.buildUrl(objectResult.url);
        } else {
          file.url = objectResult.url;
        }
        // 将后台访问url，更新fileList, 已支持图片预览和下载操作
        fileList.forEach(item => {
          if (item.uid == file.uid) {
            item.url = file.url;
          }
        });
        file.status = 'done';
      }
    } else {
      file.status = 'error';
    }
  }

  clearImage() {
    this.fileList = [];
  }
}
